#include "../http-v1/server.hpp"


void HandleClose(Channel* cha)
{
    cout<<" close: "<<cha->Fd()<<endl;
    cha->Remove();
    delete cha;

}
void HandleRead(Channel* cha)
{
    int fd=cha->Fd();
    char buf[1024]={0};
    int ret=recv(fd,buf,1023,0);//阻塞式从fd读取到buf
    if(ret<=0)
    {
        cout<<"recv failed"<<endl;
        return HandleClose(cha);
    }
    cout<<"recv data:"<<buf<<endl;
    cha->EnableWrite();//读完了就可以写了
   
}

void HandleWrite(Channel* cha)
{
    int fd=cha->Fd();
    char* data="对的";
    int ret=send(fd,data,strlen(data),0);
    if(ret<0)
    {
        cout<<"send failed"<<endl;
        return HandleClose(cha);
    }
    cha->DisableWrite();
}
void HandleError(Channel* cha)
{
    return HandleClose(cha);

}

void HandleEvent(Channel* cha)
{
    cout<<"有一个事件"<<endl;
}
void Acceptor(EventLoop*evp,Channel* lst_cha)
{
    int fd=lst_cha->Fd();
    int newfd=accept(fd,NULL,NULL);//accpet用于服务器接收客户端的连接，返回一newfd用于通信
    if(newfd<0)
    {
        cout<<"accept failed"<<endl;
        return ;
    }
    Channel* newcha=new Channel(evp,newfd);
    newcha->SetReadCallback(std::bind(HandleRead,newcha));
    newcha->SetWriteCallback(std::bind(HandleWrite,newcha));
    newcha->SetErrorCallback(std::bind(HandleError,newcha));
    newcha->SetCloseCallback(std::bind(HandleClose,newcha));
    newcha->SetEventCallback(std::bind(HandleEvent,newcha));
    newcha->EnableRead();
}
//createserver->channel->acceptor->newcha给对应fd配备函数->server开启读，等待接收client发来的事件并处理

int main()
{
   // Poller poller;
  EventLoop evp;
  cout<<"evp"<<endl;
    Socket lst_sock;
    cout<<"lst_sock"<<endl;
    lst_sock.CreateServer(8500);
    Channel channel(&evp,lst_sock.Getfd());
    cout<<"channel"<<endl;
    channel.SetReadCallback(std::bind(Acceptor,&evp,&channel));
    cout<<"SetReadCallback"<<endl;
    channel.EnableRead();
    cout<<"EnableRead"<<endl;
    while(1)
    {
        evp.start();
        cout<<"start"<<endl;    
    }
    // while(1)
    // {
    //     std::vector<Channel*> actives;
    //     poller.Poll(&actives);//阻塞等待actives内的channel
    //     for(auto& a:actives)
    //     {
    //         a->HandleEvent();// 有事件到来就处理
    //     }
    // }
    lst_sock.Close();
    return 0;
}